<?
require_once($_SERVER["DOCUMENT_ROOT"] . '/db/db.php');
$file = 'query.kml';
$where = "";
// Opens a connection to a db server.
//$list = Array('city' => 'blue', 'zip' => 'purple', 'price' => 'green');
$db = new DBConnection('dbname=assclap_realty port=5432 user=assclap_assclap password=fibo1235');
if (isset($_GET['BY']))
{
	$what = $_GET['BY'];
	$whereandorder = "WHERE $what = '$_GET[$what]' AND property_aux.rating = 1 ";
	$file = preg_replace("/[^a-z\d]/i", "", $_GET[$what]) . '.kml';
}

$sql = "SELECT property.*, property_aux.rating, property_aux.comments, x(the_geom) as lon, y(the_geom) as lat FROM property left join property_aux on (property_aux.mls_id = property.mls_id) $whereandorder ";
$Query = $db->CreateQuery($sql);

// Creates the Document.
$kml = array('<?xml version="1.0" encoding="UTF-8"?>');
$kml[] = '<kml xmlns="http://earth.google.com/kml/2.1">';
$kml[] = ' <Document>';

//$icons = Array('blue', 'green', 'purple', 'red', 'yellow');
$icons = Array(1=>'green', -1 => 'red', 0 => 'yellow');
foreach($icons as $v)
{
	$kml[] = ' <Style id="' . $v . 'Style">';
	$kml[] = ' <IconStyle id="' . $v . 'Icon">';
	$kml[] = ' <Icon>';
	$kml[] = ' <href>http://planetsnook.com/map/images/monopoly-house-' . $v . '.png</href>';
	$kml[] = ' </Icon>';
	$kml[] = ' </IconStyle>';
	$kml[] = ' </Style>';
}

$oldsd = '';
$sdIndex = -1;
// Iterates through the results, creating one Placemark for each row.
while ($row = $Query->FetchRow())
{
	// Creates a Placemark and append it to the Document.
	$kml[] = ' <Placemark id="placemark' . $row['id'] . '">';
	$kml[] = ' <name>' . htmlentities($row['price']) . '</name>';
	$kml[] = "<description>{$row['address']}</description>";
//	$kml[] = ' <name>' . htmlentities($row['address'] . ', ' . $row['city']  . ', ' . $row['state']) . '</name>';
//	$kml[] = "<description>{$row['price']} - {$row['address']}</description>";

	$kml[] = ' <name2>' . $row['rating'] . '</name2>';
	$kml[] = ' <styleUrl>#' . $icons[$row['rating']] . 'Style</styleUrl>';
	$kml[] = ' <Point>';
	$kml[] = ' <coordinates>' . $row['lon'] . ','  . $row['lat'] . '</coordinates>';
	$kml[] = ' </Point>';
	$kml[] = ' </Placemark>';
}

// End XML file
$kml[] = ' </Document>';
$kml[] = '</kml>';
$kmlOutput = join("\n", $kml);
header('Content-type: application/vnd.google-earth.kml+xml');
header('Content-disposition: attachment; filename='. $file);
echo $kmlOutput;
?>

